package com.prex.auth.authentication.third;

import com.prex.common.auth.service.LoginType;
import com.prex.common.auth.util.LoginTypeUtil;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import sun.security.util.SecurityConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname ThirdAuthenticationFilter
 * @Description 第三方登录过滤
 * @Author Created by Lihaodong (alias:小东啊) im.lihaodong@gmail.com
 * @Date 2019-09-16 11:22
 * @Version 1.0
 */
public class ThirdAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public ThirdAuthenticationFilter() {
        super(new AntPathRequestMatcher("/social", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String code = request.getParameter("code");
            String state = request.getParameter("state");
            LoginType loginType = LoginTypeUtil.getLoginType(state);
            ThirdAuthenticationToken authRequest = new ThirdAuthenticationToken(code, loginType);
            authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

}
